package com.loong.web.suppert.handle;

import java.io.IOException;

import javax.servlet.http.HttpServletRequest;

import org.springframework.http.HttpOutputMessage;
import org.springframework.http.converter.HttpMessageNotWritableException;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import com.fasterxml.jackson.core.JsonEncoding;
import com.fasterxml.jackson.core.JsonGenerator;
import com.fasterxml.jackson.core.JsonProcessingException;

/**
 * JsonP处理器
 * 
 * @author 张成轩
 */
public class JsonpHandler extends MappingJackson2HttpMessageConverter {

	/** JsonP会调方法参数 */
	private final static String CALLBACK = "callback";
	/** JsonP起始 */
	private final static String START = "(";
	/** JsonP终止ֹ */
	private final static String END = "); ";

	@Override
	protected void writeInternal(Object o, HttpOutputMessage outputMessage)
			throws IOException, HttpMessageNotWritableException {

		JsonEncoding encoding = getJsonEncoding(outputMessage.getHeaders().getContentType());
		// Json处理器
		JsonGenerator jsonGenerator = getObjectMapper().getFactory().createGenerator(outputMessage.getBody(), encoding);
		try {
			HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.currentRequestAttributes())
					.getRequest();
			// 回调方法名
			String callback = request.getParameter(CALLBACK);
			if (callback == null || callback.trim().isEmpty())
				// Json格式处理
				getObjectMapper().writeValue(jsonGenerator, o);
			else {
				// JsonP格式处理
				jsonGenerator.writeRaw(callback);
				jsonGenerator.writeRaw(START);
				getObjectMapper().writeValue(jsonGenerator, o);
				jsonGenerator.writeRaw(END);
			}
			jsonGenerator.flush();
		} catch (JsonProcessingException e) {
			throw new HttpMessageNotWritableException(e.getMessage(), e);
		}
	}
}